<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
            style="float:right"
            type="primary"
            @click="handleSearchList()"
            size="small">
          查询搜索
        </el-button>
        <el-button
            style="float:right;margin-right: 15px"
            @click="handleResetSearch()"
            size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" label-width="auto" size="small">
          <el-form-item label="自增id：">
            <el-input v-model="listQuery.id" class="input-width" clearable placeholder=""  @input="forceUpdateElement"></el-input>
          </el-form-item>
          <el-form-item label="mysql数据库：">
            <el-input v-model="listQuery.mysqlDatabaseName" class="input-width" placeholder="" clearable></el-input>
          </el-form-item>

        </el-form>
      </div>
    </el-card>

    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button type="warning" size="mini" class="btn-add" @click="handleAdd()" style="margin-left: 20px">添加
      </el-button>


    </el-card>

    <div class="table-container">
      <el-table :data="list"
                style="width: 100%;"
                v-loading="listLoading" border>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand" style="background-color: #eeeeee4f">
              <el-form-item label="mysql驱动">
                <span>{{ props.row.mysqlDriver }}</span>
              </el-form-item>
              <el-form-item label="mysql连接串">
                <span>{{ props.row.mysqlConnectUrl }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>

        <el-table-column label="自增id" align="center" prop="id"/>
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column label="mysql数据库" align="center" prop="mysqlDatabaseName"/>
        <el-table-column label="mysql用户名" align="center" prop="mysqlUsername"/>
        <el-table-column label="mysql密码" align="center" prop="mysqlPassword"/>
        <el-table-column label="创建时间" align="center" prop="createTime" width="170"/>
        <el-table-column label="更新时间" align="center" prop="updateTime" width="170"/>

        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes,prev, pager, next,jumper"
          :current-page.sync="listQuery.current"
          :page-size="listQuery.pageSize"
          :page-sizes="[5,10,15]"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="编辑数据源管理"
               :visible.sync="editDialogVisible"
               width="80%">
      <el-form :model="projectDatasource"
               ref="editForm"
               :rules="editFormRules" label-width="auto" size="small">
        <el-form-item label="备注：" prop="remark">
          <el-input maxlength="255" v-model="projectDatasource.remark"></el-input>
        </el-form-item>
        <el-form-item label="mysql数据库：" prop="mysqlDatabaseName">
          <el-input maxlength="255" v-model="projectDatasource.mysqlDatabaseName"></el-input>
        </el-form-item>
        <el-form-item label="mysql用户名：" prop="mysqlUsername">
          <el-input maxlength="255" v-model="projectDatasource.mysqlUsername"></el-input>
        </el-form-item>
        <el-form-item label="mysql密码：" prop="mysqlPassword">
          <el-input maxlength="255" v-model="projectDatasource.mysqlPassword"></el-input>
        </el-form-item>
        <el-form-item label="mysql驱动：" prop="mysqlDriver">
          <el-input maxlength="255" v-model="projectDatasource.mysqlDriver"></el-input>
        </el-form-item>
        <el-form-item prop="mysqlConnectUrl">
          <template #label>
            <span>
              mysql连接串：
              <el-tooltip placement="bottom" effect="light">
                <template #content>
                  springboot项目中连接数据库的配置信息，可以手动修改
                </template>
                <i class="el-icon-question"/>
              </el-tooltip>
            </span>
          </template>
          <el-input type="textarea" autosize v-model="projectDatasource.mysqlConnectUrl"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false" size="small">取 消</el-button>
        <el-button @click="handleTestDatasource()" size="small" type="success"
                   :loading="btnLoading">测试数据源</el-button>
        <el-button type="primary" @click="handleEditDialogConfirm()" size="small"
                   :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="新增数据源管理"
               :visible.sync="addDialogVisible"
               width="80%">
      <el-form :model="projectDatasource"
               ref="addForm"
               :rules="addFormRules" label-width="auto" size="small">
        <el-form-item label="备注：" prop="remark">
          <el-input maxlength="255" v-model="projectDatasource.remark"></el-input>
        </el-form-item>
        <el-form-item label="主机名/IP：" prop="ip">
          <el-input maxlength="255" v-model="projectDatasource.ip" @input="autoCompleteConnectUrl"></el-input>
        </el-form-item>
        <el-form-item label="端口：" prop="port">
          <el-input max="99999" type="number" min="0001" v-model="projectDatasource.port"
                    @input="autoCompleteConnectUrl"></el-input>
        </el-form-item>
        <el-form-item label="用户：" prop="mysqlUsername">
          <el-input maxlength="255" v-model="projectDatasource.mysqlUsername"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="mysqlPassword">
          <el-input maxlength="255" v-model="projectDatasource.mysqlPassword"></el-input>
        </el-form-item>
        <el-form-item label="mysql数据库：" prop="mysqlDatabaseName">
          <el-input maxlength="255" v-model="projectDatasource.mysqlDatabaseName" show-word-limit clearable
                    @input="autoCompleteConnectUrl"></el-input>
        </el-form-item>
        <el-form-item label="mysql驱动：" prop="mysqlDriver">
          <el-input maxlength="255" v-model="projectDatasource.mysqlDriver" show-word-limit clearable></el-input>
        </el-form-item>
        <el-form-item label="mysql连接串：" prop="mysqlConnectUrl">
          <template #label>
            <span>
              mysql连接串：
              <el-tooltip placement="bottom" effect="light">
                <template #content>
                  springboot项目中连接数据库的配置信息，可以手动修改
                </template>
                <i class="el-icon-question"/>
              </el-tooltip>
            </span>
          </template>
          <el-input type="textarea" autosize v-model="projectDatasource.mysqlConnectUrl" clearable></el-input>
        </el-form-item>
        <el-form-item label="">
          <template #label>
            <div>
              建库sql：
              <el-tooltip placement="bottom" effect="light">
                <template #content>
                  提交后，会自动执行sql建库。建库语句可以手动修改
                </template>
                <i class="el-icon-question"/>
              </el-tooltip>
            </div>
          </template>
          <el-input type="textarea" :autosize="{ minRows: 5, maxRows: 10}" v-model="createDataBaseSql"
                    clearable></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false" size="small">取 消</el-button>
        <el-button @click="handleTestDatasource()" size="small" type="success"
                   :loading="btnLoading">测试数据源</el-button>
        <el-button type="primary" @click="handleAddDialogConfirm()" size="small" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog title="是否要删除该数据源管理"
               :visible.sync="deleteDataTableDialogVisible"
               width="30%">
      <el-card>
        <div slot="header" class="clearfix">
          <span>同时删除数据库？</span>
        </div>
        <el-switch
            style="display: block"
            v-model="deleteOnDatabase"
            active-color="#ff4949"
            inactive-color="#13ce66"
            active-text="是"
            inactive-text="否"
            :active-value="true"
            :inactive-value="false">
        </el-switch>
      </el-card>
      <div style="color:red;">{{ deleteOnDatabase ? "请注意，数据库将一起被删除！！！" : "只删除记录，不删除数据库" }}</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDataTableDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleConfirmDelete()" size="small">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import {projectDatasourcePostRequire} from '@/api/projectDatasource'

const defaultListQuery = {
  current: 1,
  pageSize: 10,
  id: undefined,
  mysqlDatabaseName: undefined,

}
const defaultProjectDatasource = {
  id: undefined,
  ip: '127.0.0.1',
  port: '3306',
  remark: undefined,
  mysqlDatabaseName: undefined,
  mysqlDriver: 'com.mysql.cj.jdbc.Driver',
  mysqlConnectUrl: 'jdbc:mysql://127.0.0.1:3306/test?allowMultiQueries=true&useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true',
  mysqlUsername: 'root',
  mysqlPassword: undefined,
  createTime: undefined,
  updateTime: undefined,

}
export default {
  name: 'projectDatasourceList',
  data() {
    return {
      listQuery: this.$deepClone(defaultListQuery),
      list: null,
      total: null,
      listLoading: false,
      btnLoading: false,
      addDialogVisible: false,
      editDialogVisible: false,
      projectDatasource: this.$deepClone(defaultProjectDatasource),
      createDataBaseSql: '',

      addFormRules: {
        remark: [{required: true, message: '请输入备注', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
        mysqlConnectUrl: [{required: true, message: '请输入mysql连接串', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
        mysqlUsername: [{required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
        mysqlDatabaseName: [{required: true, message: '请输入数据库名称', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
        ip: [{required: true, message: '请输入ip', trigger: 'blur'},],
        port: [{required: true, message: '请输入端口', trigger: 'blur'},
          {min: 1, max: 99999, message: '长度在 1 到 99999 个字符', trigger: 'blur'},
        ],
        mysqlPassword: [{required: true, message: '请输入密码', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
        mysqlDriver: [{required: true, message: '请输入mysql驱动', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
      },
      editFormRules: {
        remark: [{required: true, message: '请输入备注', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
        mysqlDatabaseName: [{required: true, message: '请输入数据库名称', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
        mysqlUsername: [{required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
        mysqlPassword: [{required: true, message: '请输入密码', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
        mysqlDriver: [{required: true, message: '请输入mysql驱动', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
        mysqlConnectUrl: [{required: true, message: '请输入mysql连接串', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
      },
      deleteDataTableDialogVisible: false,
      currentDeleteRow: {},
      deleteOnDatabase: false,
    }
  },
  created() {
    this.listQuery.id = this.$route.query.id
    this.getList()
  },
  methods: {
    forceUpdateElement() {
      this.$forceUpdate()
    },
    autoCompleteConnectUrl() {
      this.projectDatasource.mysqlConnectUrl = 'jdbc:mysql://' + this.projectDatasource.ip +
          ':' + this.projectDatasource.port + '/' + this.projectDatasource.mysqlDatabaseName
          + '?allowMultiQueries=true&useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true'

      this.createDataBaseSql = "CREATE DATABASE IF NOT EXISTS `" + this.projectDatasource.mysqlDatabaseName + "`\n" +
          "DEFAULT CHARACTER SET UTF8;"
    },
    handleResetSearch() {
      this.listQuery = this.$deepClone(defaultListQuery)
    },
    handleSearchList() {
      this.listQuery.current = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.current = 1
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.current = val
      this.getList()
    },
    handleAdd() {
      this.addDialogVisible = true
      this.projectDatasource = this.$deepClone(defaultProjectDatasource)

    },
    handleAddDialogConfirm() {
      let params = {
        sql: this.createDataBaseSql,
        ...this.projectDatasource
      }
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          projectDatasourcePostRequire('add', params).then(response => {
            this.$message({
              message: response.message,
              type: response.status ? 'success' : 'error'
            })
            this.addDialogVisible = false
          }).finally(() => {
            this.refreshCache()
          })
        }
      })
    },
    handleConfirmDelete() {
      projectDatasourcePostRequire('delete', {
        'id': this.currentDeleteRow.id,
        deleteOnDatabase: this.deleteOnDatabase
      }).then(response => {
        this.$message({
          type: response.status ? 'success' : 'error',
          message: response.message
        })
      }).finally(() => {
        this.refreshCache()
        this.deleteDataTableDialogVisible = false
      })
    },
    handleDelete(row) {
      this.currentDeleteRow = row
      this.deleteDataTableDialogVisible = true
      this.deleteOnDatabase = false
    },
    handleUpdate(row) {
      this.editDialogVisible = true
      this.projectDatasource = this.$deepClone(row)
    },
    handleTestDatasource() {
      projectDatasourcePostRequire('testDatasource', this.projectDatasource).then(response => {
        this.$message({
          message: response.message,
          type: response.status ? 'success' : 'error'
        })
      }).finally(() => {
        this.refreshCache()
      })
    },
    handleEditDialogConfirm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true
          projectDatasourcePostRequire('update', this.projectDatasource).then(response => {
            this.$message({
              message: response.message,
              type: response.status ? 'success' : 'error'
            })
            this.editDialogVisible = false
          }).finally(() => {
            this.refreshCache()
            this.btnLoading = false
          })
        }
      })
    },
    getList() {
      this.listLoading = true
      projectDatasourcePostRequire('listPage', this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.data.records
        this.total = response.data.total
      })
    },
    refreshCache() {
      this.getList()
    }
  }
}
</script>
<style>
.demo-table-expand label {
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-left: 10px;
  width: 100%;
}
</style>
